/* eslint-disable no-console */
import React, { useState, useEffect } from 'react';
import {
    View, Text, TextInput, Platform, Keyboard, NativeEventEmitter,
    TouchableOpacity, Switch, NativeModules,
} from 'react-native';
import PropTypes from 'prop-types';
import DateTimePicker from '@react-native-community/datetimepicker';
import {
    WhiteSpace, WingBlank, Button, Tag, Toast, Modal,
} from '@ant-design/react-native';
import moment from 'moment';
import ReactNativeAN from 'react-native-alarm-notification';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { taskdetails, editTask } from '../../comconfig/sqlfun';
import styles from './styles';

const { RNAlarmNotification } = NativeModules;
const RNEmitter = new NativeEventEmitter(RNAlarmNotification);

const alarmNotifData = {
    title: '您有一个任务提醒',
    message: '尽快确认',
    channel: 'my_channel_id',
    small_icon: 'ic_launcher',
    large_icon: 'ic_launcher',
    data: { foo: 'bar' },
    sound_name: 'nyan_cat.mp3',
    has_button: false,
};

const AddImpWork = ({ navigation, route }) => {
    const [details, setDetails] = useState({});
    const [fireDate, setFireDate] = useState(ReactNativeAN.parseDate(new Date(Date.now() + 1000)));
    const [update, setUpdate] = useState([]);
    const [alarmId, setAlarmId] = useState(0);
    const getdetails = async (id) => {
        const info = await taskdetails(id);
        await setDetails(JSON.parse(info));
    };
    const { rowid, getList } = route.params;

    useEffect(() => {
        getdetails(rowid);
    }, []);
    const [date, setDate] = useState(new Date());
    const [mode, setMode] = useState('date');
    const [show, setShow] = useState(false);
    const [selDateTime, setDateTime] = useState(moment(new Date()).format('yyyy-MM-DD HH:mm:ss'));
    const [titleVal, onChangeTitleVal] = useState('');
    const [textVal, onChangeTextVal] = useState('');
    const [importantCode, setImportantCode] = useState('0');
    const [isEnabled, setIsEnabled] = useState(false);
    // const rowids = [rowid];

    useEffect(() => {
        if (JSON.stringify(details) !== '{}' && details.datetime !== null) {
            setIsEnabled(true);
            setDateTime(details.datetime);
            setAlarmId(parseInt(details.alarmid, 10));
        }
        onChangeTitleVal(details.title);
        onChangeTextVal(details.task);
        setImportantCode(details.impcode);
    }, [details]);

    const toggleSwitch = () => {
        setIsEnabled(previousState => !previousState);
    };

    const onChange = (event, selectedDate) => {
        const currentDate = selectedDate || date;
        setShow(false);
        setDate(currentDate);
        setFireDate(moment(currentDate).format('DD-MM-yyyy HH:mm:00'));
        setDateTime(moment(currentDate).format('yyyy-MM-DD HH:mm:00'));
    };

    const showMode = (currentMode) => {
        setShow(true);
        setMode(currentMode);
    };

    const showDatepicker = () => {
        showMode('date');
    };

    const showTimepicker = () => {
        showMode('time');
    };

    const changeImpCode = (code) => {
        setImportantCode(code);
    };

    const edit = () => {
        if (titleVal === ''
        || importantCode === '0'
        || titleVal.trim().length === 0
        ) {
            Modal.alert(
                <Text style={{ color: '#0F8DE9' }}>请输入完整</Text>,
                null,
                [
                    { text: 'OK' },
                ],
            );
            return;
        }
        if (isEnabled) {
            editTask(rowid, titleVal, textVal, selDateTime, importantCode, alarmId);
            getList();
            navigation.goBack();
        } else {
            editTask(rowid, titleVal, textVal, null, importantCode, 0);
            getList();
            navigation.goBack();
        }
    };
    // const delOne = () => {
    //     Alert.alert(
    //         '提醒',
    //         '是否删除',
    //         [
    //             {
    //                 text: '是',
    //                 onPress: async () => {
    //                     await delImptask(rowids);
    //                     await getList();
    //                     await navigation.goBack();
    //                 },
    //             },
    //             { text: '否' },
    //         ],
    //     );
    // };
    const deleteAlarm = async () => {
        if (alarmId !== 0) {
            const id = parseInt(alarmId, 10);
            ReactNativeAN.deleteAlarm(id);
            setAlarmId(0);
            Toast.info('已删除闹钟', 1, undefined, false);
        }
    };
    // 设置闹钟
    const setAlarm = async () => {
        const armdetails = {
            ...alarmNotifData,
            title: titleVal,
            message: textVal.trim().length === 0 ? '请确认' : textVal,
            fire_date: fireDate,
        };
        try {
            const alarm = await ReactNativeAN.scheduleAlarm(armdetails);
            setAlarmId(alarm.id);
            if (alarm) {
                setUpdate([...update, { date: `alarm set: ${fireDate}`, id: alarm.id }]);
            }
            Toast.info(`将于${moment(selDateTime).diff(moment(), 'minutes')}分后提醒`);
        } catch (e) {
            Toast.info('设置闹钟失败', 1, undefined, false);
        }
    };

    const showPermissions = () => {
        ReactNativeAN.checkPermissions((permissions) => {
            console.log(permissions);
        });
    };

    useEffect(() => {
        const subscribeDismiss = RNEmitter.addListener(
            'OnNotificationDismissed',
            (data) => {
                const obj = JSON.parse(data);
                console.log(`notification id: ${obj.id} dismissed`);
            },
        );

        const subscribeOpen = RNEmitter.addListener(
            'OnNotificationOpened',
            (data) => {
                console.log(data);
                const obj = JSON.parse(data);
                console.log(`app opened by notification: ${obj.id}`);
            },
        );

        if (Platform.OS === 'ios') {
            showPermissions();

            ReactNativeAN.requestPermissions({
                alert: true,
                badge: true,
                sound: true,
            }).then(
                (data) => {
                    console.log('RnAlarmNotification.requestPermissions', data);
                },
                (data) => {
                    console.log('RnAlarmNotification.requestPermissions failed', data);
                },
            );
        }
        return () => {
            subscribeDismiss.remove();
            subscribeOpen.remove();
        };
    }, []);

    useEffect(() => {
        if (!isEnabled) {
            deleteAlarm();
        }
    }, [isEnabled]);

    navigation.setOptions({
        headerRight: () => (
            <TouchableOpacity
                onPress={() => {
                    edit();
                }}
            >
                <AntDesign
                    name="form"
                    size={26}
                    color="#017BFF"
                    style={{ marginRight: 5 }}
                />
            </TouchableOpacity>
        ),
    });
    return (
        <View>
            <TouchableOpacity
                onPress={() => { Keyboard.dismiss(); }}
                activeOpacity={1}
            >
                <WingBlank size="sm">
                    <TextInput
                        placeholder="标题"
                        placeholderTextColor="#5d5d7e"
                        style={{
                            height: 60, borderColor: 'gray', borderWidth: 0, fontSize: 30,
                        }}
                        onChangeText={text => onChangeTitleVal(text)}
                        value={titleVal}
                    />
                    <TextInput
                        multiline
                        placeholder="添加事务..."
                        placeholderTextColor="#5d5d7e"
                        style={styles.textInput}
                        maxLength={200}
                        onChangeText={text => onChangeTextVal(text)}
                        value={textVal}
                        returnKeyLabel="done"
                    />
                    <WhiteSpace size="sm" />
                    <View style={{ flexDirection: 'row' }}>
                        <Text style={{ fontSize: 16 }}>设置提醒时间</Text>
                        <Switch
                            trackColor={{ false: '#5d5d7e', true: '#81b0ff' }}
                            thumbColor={isEnabled ? '#108EE9' : '#fff'}
                            onValueChange={toggleSwitch}
                            value={isEnabled}
                        />
                    </View>
                    {isEnabled && (
                        <>
                            <View style={{ flexDirection: 'row' }}>
                                <Button
                                    type="primary"
                                    style={styles.timeButton}
                                    onPress={showDatepicker}
                                >
                                    {moment(selDateTime).format('yy年MM月D日')}
                                </Button>
                                <Button
                                    type="primary"
                                    style={styles.timeButton}
                                    onPress={showTimepicker}
                                >
                                    {moment(selDateTime).format('HH时mm分')}
                                </Button>
                                <Button
                                    style={styles.timeButton}
                                    onPress={() => setAlarm()}
                                >
                                    <Text
                                        style={{ color: '#0F8DE9' }}
                                    >
                                        确认
                                    </Text>
                                </Button>
                            </View>
                        </>
                    )
                    }
                    {show && (
                        <DateTimePicker
                            textColor="#108EE9"
                            testID="dateTimePicker"
                            value={date}
                            mode={mode}
                            is24Hour
                            display="default"
                            onChange={onChange}
                        />
                    )}
                    <WhiteSpace size="sm" />
                    <Text style={{ fontSize: 16 }}>重要程度</Text>
                    <WhiteSpace size="sm" />
                    <View style={{ flexDirection: 'row' }}>
                        <Tag
                            style={styles.tag}
                            selected={importantCode === '1'}
                            onChange={() => { changeImpCode('1'); }}
                        >
                            紧急事务
                        </Tag>
                        <Tag
                            style={styles.tag}
                            selected={importantCode === '2'}
                            onChange={() => { changeImpCode('2'); }}
                        >
                            重要事务
                        </Tag>
                        <Tag
                            style={styles.tag}
                            selected={importantCode === '3'}
                            onChange={() => { changeImpCode('3'); }}
                        >
                            一般事务
                        </Tag>
                    </View>
                    {/* <Button
                        style={styles.del}
                        type="primary"
                        onPress={() => {
                            delOne();
                        }}
                    >
                        删除
                    </Button>
                    <Button
                        style={styles.done}
                        type="primary"
                        onPress={() => {
                            edit();
                        }}
                    >
                        编辑
                    </Button> */}
                </WingBlank>
            </TouchableOpacity>
        </View>
    );
};
AddImpWork.defaultProps = {
    route: {},
};
AddImpWork.propTypes = {
    route: PropTypes.objectOf(PropTypes.any),
};
export default AddImpWork;
